<template>
  <div style="padding: 0px; margin: 0px">
    <div style="float: left; width: 100%">
      <div class="consuleWarrp" :style="{ height: heightY }">
            <!-- 左侧树形结构 -->
            <div class="consultLeft" :style="{ height: heightY }">
              <div style="padding: 20px">
                <span
                    style="
                      background-color: rgba(51, 122, 183, 1);
                      width: 4px;
                      height: 18px;
                    "
                    >|</span
                  >
                  &nbsp;<b>标签分组</b>
              </div>
               <div style="padding: 20px;overflow:auto;">
                <vxe-table
                    resizable
                    show-overflow
                    style="overflow-y: scroll;"
                    :align="(allAlign = 'center')"
                    ref="xTable"
                    :tree-config="{transform: true, rowField: 'ID', parentField: 'PAREN_ID'}"
                    :data="tableData"
                    @cell-dblclick="onLeftTableRowClick"
                    :highlight-current-row="true"
                    >
                    <vxe-column field="TAG_NAME" title="分类" tree-node width="150"></vxe-column>
                    <vxe-column title="操作" width="250">
                      <template #default="{ row }">
                        <vxe-button type="text" status="primary" @click="insertRow(row)">新增下级</vxe-button>
                        <vxe-button type="text" status="primary" @click="removeRow(row.TAG_BM,row.ID)">删除</vxe-button>
                        <vxe-button type="text" status="primary" @click="editRow(row)">修改</vxe-button>
                      </template>
                    </vxe-column>
                  </vxe-table>
               </div>
            </div>
            <!-- 根据哪个menu来切换对应的表格 -->
              <!-- 右侧表格 -->
            <div class="consultRight" >
              <div style="padding: 20px">
                <span
                  style="
                    background-color: rgba(51, 122, 183, 1);
                    width: 4px;
                    height: 18px;
                  "
                  >|</span
                >
                &nbsp;<b>标签详情</b>
                <el-button
                  style="float: right"
                  type="primary"
                  plain
                  icon="el-icon-circle-plus-outline"
                  @click="handleClickAdd"
                >
                  新增
                </el-button>
              </div>
              <div style="padding:20px;height:720px;overflow:auto;">
                  <vxe-table
                  resizable
                  :align="(allAlign = 'center')"
                  border
                  ref="xTable1"
                  :tree-config="{transform: true, rowField: 'ID', parentField: 'PAREN_ID'}"
                  :data="tableDataChildren"
                  style="overflow-y: scroll;"
                >
                  <vxe-column field="TAG_NAME" title="标签名"></vxe-column>
                  <vxe-column field="SORT" title="排序值" sortable></vxe-column>
                  <vxe-column field="TAG_JP" title="简拼"></vxe-column>
                  <vxe-column field="TAG_BM" title="标签编码" sortable></vxe-column>
                  <vxe-column field="TAG_TYPE" title="标签类型"></vxe-column>
                  <vxe-column field="IS_CONSULT" title="是否定义"></vxe-column>
                  <vxe-column title="操作" width="300">
                    <template slot-scope="scope">
                      <el-button size="small" type="danger" plain
                        @click="handleClickDelete(scope.row.TAG_BM,scope.row.ID)"
                        >删除</el-button>
                      <el-button @click="handleClickEdit(scope.row)" size="small">修改</el-button>
                      <el-button @click="handleClickTag(scope.row)" size="small" type="primary">标签定义</el-button>
                    </template>
                  </vxe-column>
                </vxe-table>
              </div>
              <div class="row" style="width: 100%;">
              <div style="width: 80%;float: right">
                  <vxe-pager background align="right" :current-page.sync="pages.currentPage"
                      :page-size.sync="pages.pageSize" 
                      :total="pages.totalResult"
                      :page-sizes="[20, 50, 100, 500, 1000]"
                      :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
                      @page-change="handlePageChange">
                  </vxe-pager>
              </div>
              <div style="width: 20%;float: right;background-color: white;height: 48px">
                   
              </div>
          </div>
            </div>
      </div>

      <!-- 新增子节点的弹框 -->
      <el-dialog 
         :visible.sync="visibleChildren" 
         :title="titleChildren"
         :close-on-click-modal="false"
          top="10vh"
          :close-on-press-escape="false"
         >
          <el-form
             :model="formChildren" ref="formChildren" label-width="80px" :label-position="labelPosition">
            <el-form-item label="上级分类" prop="tagName">
              <el-input v-model="formChildren.topTagName" :disabled="true" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="分类" prop="tagName"
              :rules="[{ required: true, message: '分类名称不能为空', trigger: 'blur'}]">
              <el-input v-model="formChildren.tagName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item 
               label="排序值"
               prop="sort"
              :rules="[
                { required: true, message: '请输入排序值',trigger: 'blur'},
                { type: 'number', message: '排序值必须为数字值',trigger: 'blur'}
              ]"
            >
              <el-input v-model.number="formChildren.sort" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="visibleChildren = false">取 消</el-button>
            <el-button type="primary" @click="saveChildren()">确 定</el-button>
          </div>
      </el-dialog>

      <!-- 标签详情的修改和新增  -->
      <el-dialog 
        :visible.sync="visible" 
        :title="title"
        :close-on-click-modal="false"
        append-to-body
        top="10vh"
        :close-on-press-escape="false"
       >
        <el-form :model="form" ref="formList" label-width="80px" :label-position="labelPosition">
          <el-form-item label="标签名" 
              prop="tagName"
              :rules="[{ required: true, message: '标签名不能为空', trigger: 'blur'}]">
            <el-input v-model="form.tagName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="排序" prop="sort"
              :rules="[
                { required: true, message: '请输入排序值',trigger: 'blur'},
                { type: 'number', message: '排序值必须为数字值',trigger: 'blur'}
              ]">
            <el-input v-model.number="form.sort" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="简拼" prop="Jp" 
          :rules="[{ required: true, message: '简拼不能为空', trigger: 'blur'}]">
            <el-input v-model="form.Jp" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="save()">确 定</el-button>
        </div>
      </el-dialog>


       <!-- 标签详情的标签定义 -->
      <el-dialog 
       :visible.sync="visibleTag" 
       title="标签定义"
       :close-on-click-modal="false"
        append-to-body
        top="10vh"
        :close-on-press-escape="false"
       >
        <el-form :model="formTag" ref="formTag" label-width="80px" :label-position="labelPosition">
          <el-form-item label="标签名称"  
                        prop="tagName"
                        :rules="[{ required: true, message: '标签名称不能为空', trigger: 'blur'}]">
            <el-input v-model="formTag.tagName" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="定义key" prop="tagKey"
              :rules="[
                { required: true, message: '请输入key',trigger: 'blur'},
                { type: 'number', message: 'key值必须为数字值',trigger: 'blur'}
              ]">
            <el-input v-model.number="formTag.tagKey" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="拼音" prop="pinyin"
                :rules="[{ required: true, message: '备注不能为空', trigger: 'blur'},
                {pattern: /^[a-zA-Z]+$/, message: '只能输入英文字符', trigger: 'blur'}]">
            <el-input v-model="formTag.pinyin" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="排序" prop="sort"
              :rules="[
                { required: true, message: '请输入排序值',trigger: 'blur'},
                { type: 'number', message: '排序值必须为数字值',trigger: 'blur'}
              ]">
            <el-input v-model.number="formTag.sort" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="备注"  prop="notes"
              :rules="[{ required: true, message: '备注不能为空', trigger: 'blur'}]">
            <el-input
              autocomplete="off"
              type="textarea"
              placeholder="请输入内容"
              v-model="formTag.notes"
              maxlength="400"
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="visibleTag = false">取 消</el-button>
          <el-button type="primary" @click="saveTag()">确 定</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import { getCategoryList,saveCategory,delCategory,updateCategory,
         getConsultData,savaConsult,getCategoryByPage } from '@/api/students/organization/category';
export default {
  data() {
    return {
      heightY: window.innerHeight - 100 + 'px',
      labelPosition:"right",
      tableDataChildren: [],
      form: {
        sort: "",
        tagName: "",
        Jp: "",
      },
      formChildren:{
            topTagName:"",
            tagName: "",
            sort:'',
      },
      formTag:{
        tagName: "",
        tagKey: "",
        pinyin: "",
        sort:"",
        notes:'',
      },
      pages:{
          currentPage: 1,
          pageSize: 20,
          totalResult: 0
      },
      title:'',
      tableData: [],
      visible:false,
      visibleTag:false,
      visibleChildren:false,
      row:'',
      titleChildren:"",
      rowDblclick:"",
      editRows:"",
      rowTag:"",
      isRowDblclick:[],
    };
  },
  created () {
    this.refreshRulesData();
    this.refreshRulesList();
  },
  methods: {
    // 刷新页面
    refreshRulesData() {
      this.getCategoryList();
    },
    getCategoryList(){
        const params = {
          type:"G"
        }
        getCategoryList(params).then((response) => {
            // console.log(response,"数据")
            this.tableData = response;
        })
    },
    refreshRulesList() {
      this.onLeftTableRowClick(this.rowDblclick);
    },
    onLeftTableRowClick({ row }) {
    if (!this.isRowDblclick[row.TAG_BM]) { // 判断该分组是否已经双击过
      this.isRowDblclick = { ...this.isRowDblclick, [row.TAG_BM]: true }; // 设置该分组已双击
      this.rowDblclick = row;
      const params = {
        type: "B",
        tagBm: row.TAG_BM,
      };
      getCategoryList(params).then((response) => {
        this.tableDataChildren = response;
      });
      const param = {
        type: "B",
        tagBm: row.TAG_BM,
        page: this.pages.currentPage,
        rows: this.pages.pageSize,
      };
      getCategoryByPage(param).then((res) => {
        this.pages.totalResult = res.totle; // 设置总记录数
      });
    }
    },
    insertRow (row) {
      this.titleChildren = "新增子节点"
      this.row = row;
      this.visibleChildren = true;
      this.formChildren.topTagName = row.TAG_NAME;
      this.formChildren.tagName = "";
      this.formChildren.sort = ""
    },
    editRow(row){
      this.titleChildren = "修改子节点"
      this.row = row;
      this.formChildren.tagName = row.TAG_NAME
      this.formChildren.sort = row.SORT
      this.formChildren.topTagName = row.TAG_NAME;
      this.visibleChildren = true;
    },
    saveChildren(){
      if(this.formChildren.tagName === '' || this.formChildren.sort === ''){
          this.$message({
            message: '请填写完整信息',
            type: 'warning'
          })
          return
        }
      const params = {
        parentId:this.row.ID,
        tagName:this.formChildren.tagName,
        sort:this.formChildren.sort,
        tagType:"G",
        parentBm:this.row.TAG_BM,
      }
      if(this.titleChildren === "新增子节点"){
        saveCategory(params).then((res)=>{
          if(parseInt(res.code) === 200){
            this.$message.success('新增成功')
            this.visibleChildren = false
            this.refreshRulesData();
          }else{
            this.$message({
                message: res.message,
                type: 'warning'
            })
          }
        }).catch(()=>{
        })
      }else if(this.titleChildren === "修改子节点"){
        const param = {
          id:this.row.ID,
          tagName:this.formChildren.tagName,
          sort:this.formChildren.sort,
          tagType:"G",
          parentBm:this.row.TAG_BM,
        }
        updateCategory(param).then((res)=>{
          if(res.code == 200){
            this.$message.success('修改成功')
            this.visibleChildren = false
            this.refreshRulesData();
          }else{
            this.$message({
                message: res.message,
                type: 'warning'
            })
          }
        })
      }
    },
    removeRow (tag_bm,id) {
      const params = {
          tagBm:tag_bm,
          id:id,
      }
      this.$confirm('是否确定删除?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'success'
        }).then(() => {
          delCategory(params).then((res) => {
                let that = this
                if (res.code == 200) {
                    that.$message({
                        message: '删除成功',
                        type: 'success'
                    })
                    this.refreshRulesData();//刷新页面
                } else {
                    that.$message({
                        message: res.message,
                        type: 'warning'
                    })
                }
            })
        }).catch(() => {
          
        })
    },

    // 新增和编辑
    handleClickAdd() {
      const selectedGroup = this.rowDblclick.TAG_BM; // 获取当前选中的分组
      if (!selectedGroup) {
        this.$confirm("请先选择左侧的标签分组", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        return;
      }

      this.title = "新增";
      this.visible = true;
      this.form.sorts = "";
      this.form.name = "";
      this.form.number = "";

      // 重置该分组的双击状态为 false
      this.isRowDblclick = { ...this.isRowDblclick, [selectedGroup]: false }
    },
    handleClickEdit(row) {
      this.title = "修改"
      this.visible = true;
      this.editRows = row;
      this.form.tagName = row.TAG_NAME
      this.form.sort = row.SORT
      this.form.Jp = row.TAG_JP
    },
    save(){
      if(this.form.tagName === '' || this.form.sort === '' || this.form.Jp === ""){
          this.$message({
            message: '请填写完整信息',
            type: 'warning'
          })
          return
      }
      const params = {
        parentId:this.rowDblclick.ID,
        tagName:this.form.tagName,
        sort:this.form.sort,
        tagJp:this.form.Jp,
        tagType:"B",
        parentBm:this.rowDblclick.TAG_BM,
      }
      if(this.title === "新增"){
        saveCategory(params).then((res)=>{
          if(parseInt(res.code) === 200){
            this.$message({
              message: res.message,
              type:"success",
            })
            this.visible = false
            // 手动更新数据
            const params = {
              type: "B",
              tagBm: this.rowDblclick.TAG_BM
            };
            getCategoryList(params).then((response) => {
            this.tableDataChildren = response;
            });
          }else{
            this.$message({
                message: res.message,
                type: 'warning'
            })
          }
        }).catch(()=>{
        })

      }else if(this.title === "修改"){
        const param = {
          id:this.editRows.ID,
          tagName:this.form.tagName,
          sort:this.form.sort,
          tagJp:this.form.Jp,
          tagType:"B",
          parentBm:this.editRows.TAG_BM,
        }
        updateCategory(param).then((res)=>{
          if(parseInt(res.code) === 200){
            this.$message({
              message: res.message,
              type:"success",
            })
            this.visible = false;
            const params = {
              type: "B",
              tagBm: this.rowDblclick.TAG_BM
            };
            getCategoryList(params).then((response) => {
            this.tableDataChildren = response;
            });
          }else{
            this.$message({
                message: res.message,
                type: 'warning'
            })
          }
        })
      }
    },
    handleClickDelete(tag_bm,id){
      const params = {
          tagBm:tag_bm,
          id:id,
      }
      this.$confirm('删除时会把标签定义一起删除,是否确定删除?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'success'
        }).then(() => {
          delCategory(params).then((res) => {
                let that = this
                if (res.code == 200) {
                    that.$message({
                        message: '删除成功',
                        type: 'success'
                    })
                    const params = {
                      type: "B",
                      tagBm: this.rowDblclick.TAG_BM
                    };
                    getCategoryList(params).then((response) => {
                    this.tableDataChildren = response;
                    });
                } else {
                    that.$message({
                        message: res.message,
                        type: 'warning'
                    })
                }
            })
        }).catch(() => {
          
        })
    },
    handleClickTag(row){
      this.rowTag = row;
       this.visibleTag = true;
       const params = {
         ctegoryId:row.ID,
       }
       getConsultData(params).then((res)=>{
        this.formTag.tagName = row.TAG_NAME;
        if (res.resultdata) {
          this.formTag.tagKey = res.resultdata.TAG_KEY;
          this.formTag.pinyin = res.resultdata.PINYIN;
          this.formTag.sort = res.resultdata.SORT;
          this.formTag.notes = res.resultdata.NOTES;
        } else {
          this.formTag.tagKey = "";
          this.formTag.pinyin = "";
          this.formTag.sort = "";
          this.formTag.notes = "";
        }
       })
    },
    saveTag(){
      if(this.formTag.tagName === '' || this.formTag.sort === '' || this.formTag.tagKey === "" || this.formTag.pinyin === "" || this.formTag.notes === ""){
          this.$message({
            message: '请填写完整信息',
            type: 'warning'
          })
          return
      }else if (!/^[A-Za-z]+$/.test(this.formTag.pinyin)) {
        this.$message({
          message: '拼音必须为英文字符',
          type: 'warning'
        });
        return;
      }
      const params = {
          tagName:this.rowTag.TAG_NAME,
          tagKey: this.formTag.tagKey,
          pinyin: this.formTag.pinyin,
          sort:this.formTag.sort,
          parentId:this.rowTag.ID,
          parentBm:this.rowTag.TAG_BM,
          notes:this.formTag.notes,
       }
       savaConsult(params).then((res)=>{
          if(res.code == 200){
            this.$message({
              message: res.message,
              type:"success",
            })
            this.visibleTag = false;
          }else{
            this.$message({
              message: res.message,
              type:"warning",
            })
          }
       })
    },
    // 分页
    handlePageChange({ currentPage, pageSize }){
      this.pages.currentPage = currentPage
      this.pages.pageSize = pageSize
      this.onLeftTableRowClick();
    },
  },
};
</script>
<style scoped>
.consuleWarrp{
    width: 100%;
    background-color: white;
}
.consultLeft{
    float: left;
    width: 25%;
    border-right:1px solid #ccc;
}
.consultRight{
    float: left;
    width: 75%;
}
.el-menu-vertical-demo{
    text-align: center;
  }
.el-menu-item span{
    font-size: 18px;
    font-weight: bolder;
}
>>>.el-input--small .el-input__inner{
  width: 500px;
  margin-left: 20px;
}


>>>.el-textarea__inner{
  width: 500px;
  margin-left: 20px;
}
>>>.el-form-item__error{
  margin-left: 20px;
}
>>>.el-textarea .el-input__count{
  right: 140px;
}
>>>.el-dialog{
  width: 750px;
}
</style>